<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use App\Model\User;

class GuanliyuanController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = user::orderBy('id','desc')->where('nickname',"管理员")->paginate(5);
        return view('admin.guanliyuanList')->with('users',$users);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.guanliyuanAdd');
    }

    /**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
    public function store(Request $request)
    {
        //验证规则
        $messages = [
            'email.required' => '邮箱必须填写',
            'name.required' => '用户名必须填写',
            'email.email' => '邮箱规则不合法',
            'phone.required' => '手机必须填写',
            'phone.digits' => '手机号码格式不正确',
            'password.required' => '密码必须填写',
            'password.confirmed' => '两次密码输入不一致',
        ];

        $this->validate($request, [
            'name' => 'required',
            'password' => 'required|confirmed',
            'email' => 'required|email',
            'phone' => 'required|digits:11',
        ],$messages);

        //执行添加操作
        $user = new user();
        $user->name = $request->name;
        $user->password = Hash::make($request->password);
        $user->email = $request->email;
        $user->phone = $request->phone;
        $user->nickName = $request->nickName;
        $user->save();
        return redirect('/guanliyuan');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //管理员删除
        $user = User::find($id)->delete();
        return redirect('/guanliyuan');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //编辑管理员信息
        $user = User::find($id);
        return view('admin.guanliyuanEdit')->with('user',$user);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //编辑管理员
        DB::table('users')->where('id', '=', $id)->update(['password' => $request->password,'email' => $request->email,'nickName' => $request->nickName,'phone' => $request->phone]);
        return back();
    }

}
